package com.example.config.security.authority;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.pojo.Menu;
import com.example.service.IMenuService;
import com.example.service.impl.MenuServiceImpl;
import com.example.util.SystemRole;
import com.example.vo.respvo.MenuAuthenticationVo;
import org.apache.naming.EjbRef;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.util.pattern.PathPatternRouteMatcher;
import springfox.documentation.service.ClientCredentialsGrant;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 自定义权限控制 2
 * 根据请求url分析请求所需的角色
 * @author wsl
 */
@Service("securityMetadataSource")
public class SecurityMetadataSourceImpl implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private IMenuService menuService;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        String requestUrl = cutUrl(((FilterInvocation) o).getRequestUrl());//获取用户的请求url

        //1.不在系统菜单管理范围内的资源。
        List<Menu> menus = menuService.list(new QueryWrapper<Menu>().likeRight("path", requestUrl));
        if(menus.size()==0){
            return SecurityConfig.createList("NONE_LIMITATION");//未受限制资源
        }

        //2.系统管理菜单资源
        List<Menu> list = menuService.list();//系统管理的菜单
        List<String> requireAuthMenu = new ArrayList<>();//需要认证的菜单集合
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        for (Menu menu : list) {
            if(antPathMatcher.match(menu.getPath(),requestUrl)){
                if(menu.getRequireAuth()==0){
                    return SecurityConfig.createList(SystemRole.ROLE_LOGIN);//不需要权限认证，登录即可访问的资源
                }
                requireAuthMenu.add(menu.getPath());
            }
        }
        List<String> roles = menuService.getMenusWithRole(requireAuthMenu);//获取受限资源的访问角色
        return SecurityConfig.createList(roles.toArray(new String[0]));
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }

    public static String cutUrl(String rawRequestUrl){
        int i = rawRequestUrl.indexOf("?");
        if(i == -1){//不存在?拼接请求字符
            return rawRequestUrl;
        }
        return rawRequestUrl.substring(0,i);
    }
}
